package com.hbsoft.lms.controller;

import com.hb.bean.CallResult;
import com.hb.controller.ABaseController;
import com.hbsoft.common.constant.Constant;
import com.hbsoft.common.enumtype.AreaUserRoleEnum;
import com.hbsoft.lms.bean.*;
import com.hbsoft.lms.dao.BankAreaBeanDao;
import com.hbsoft.lms.dao.BankBeanDao;
import com.hbsoft.lms.dao.BankBranchBeanDao;
import com.hbsoft.lms.dao.service.*;
import com.hbsoft.lms.service.BankAreaAuthService;
import com.hbsoft.lms.service.BankAreaService;
import com.hbsoft.lms.service.CustomerManagerService;
import com.hbsoft.lms.vo.DictVo;
import com.hbsoft.lms.vo.TreeVo;
import com.hbsoft.util.GsonUtil;
import com.hbsoft.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.geom.Area;
import java.util.*;

@RestController
@RequestMapping(value = "", produces = "application/json;charset=UTF-8")
public class BankAreaController extends ABaseController {

    @Autowired
    BankAreaBeanDaoService bankAreaBeanDaoService;

    @Autowired
    BankAreaBeanDao bankAreaBeanDao;

    @Autowired
    BankBeanDaoService bankBeanDaoService;

    @Autowired
    BankBranchBeanDaoService bankBranchBeanDaoService;

    @Autowired
    BankBeanDao bankBeanDao;

    @Autowired
    BankBranchBeanDao bankBranchBeanDao;

    @Autowired
    AreaUserBeanDaoService areaUserBeanDaoService;

    @Autowired
    CustomerManagerService customerManagerService;

    @Autowired
    BankAreaService bankAreaService;

    @Autowired
    BankAreaAuthService bankAreaAuthService;

    @Autowired
    BankAreaAuthBeanDaoService bankAreaAuthBeanDaoService;

    @RequestMapping("getBankAreaList")
    public String getBankAreaList(BankAreaBean bankAreaBean){
        Map<String,Object> map = new HashMap<>();
        try {
           map =  bankAreaBeanDaoService.getPagingData(bankAreaBean);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","获取失败");
        }
        return GsonUtil.toJson(map);
    }

    @RequestMapping("addBankArea")
    public String addBankArea(@Validated  BankAreaBean bankAreaBean){
        CallResult<String> result = new CallResult<>();
        try {
            BankAreaBean param = new BankAreaBean();
            param.setName(bankAreaBean.getName());
            BankAreaBean ba = bankAreaBeanDaoService.getByField(param);
            if (ba == null) {
                String code = bankAreaBeanDao.selectMaxCode();
                if (isEmpty(code)) {
                    code = Constant.STARTCODE;
                } else {
                    code = StringUtil.getCode(3, code);
                }
                bankAreaBean.setCode(code);
                bankAreaBean.setCreateOn(new Date());
                bankAreaBean.setCreateBy(String.valueOf(user_id_prikey));
                bankAreaBean.setUpdateBy(String.valueOf(user_id_prikey));
                bankAreaBean.setUpdateOn(new Date());
                bankAreaBeanDaoService.add(bankAreaBean);
                result.setCode(0);
                result.setMsg("操作成功");
            } else {
                result.setCode(400);
                result.setMsg("名称重复");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }

    @RequestMapping("updateBankArea")
    public String updateBankArea(@Validated  BankAreaBean bankAreaBean){
        CallResult<String> result = new CallResult<>();
        try {
            if(bankAreaBean.getId_prikey() == null){
                result.setCode(400);
                result.setMsg("主键参数有误");
            }else{
                bankAreaBean.setUpdateOn(new Date());
                bankAreaBean.setUpdateBy(String.valueOf(user_id_prikey));
                bankAreaBeanDaoService.set(bankAreaBean);
                result.setCode(0);
                result.setMsg("操作成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }

    @RequestMapping("deleteBankArea")
    public String deleteBankArea(Integer id_prikey){
        CallResult<String> result = new CallResult<>();
        try {
            if(id_prikey == null){
                result.setCode(400);
                result.setMsg("主键参数有误");
            }else{
                bankAreaBeanDaoService.removeOne(id_prikey);
                result.setCode(0);
                result.setMsg("操作成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }


    @RequestMapping("getAllBankArea")
    public String getAllBankArea(){
        CallResult<List<DictVo>> result = new CallResult<>();
        try {
            List<BankAreaBean> list = bankAreaBeanDao.findAll(null);
            List<DictVo> voList = new ArrayList<>();
            if(list!= null && list.size() > 0){
                for(BankAreaBean b : list){
                    DictVo vo = new DictVo();
                    vo.setCode(b.getCode());
                    vo.setName(b.getName());
                    voList.add(vo);
                }
                result.setCode(0);
                result.setMsg("操作成功");
            }
            result.setData(voList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return GsonUtil.toJson(result);
    }


    @RequestMapping("getBankList")
    public String getBankList(BankBean bankBean){
        Map<String,Object> map = new HashMap<>();
        try {
            CallResult<String> result = getAreaCodeByLogin(AreaUserRoleEnum.AREA_USER_ROLE_SHIB.getCode());
            if(result.isExec()){
                bankBean.setAreaCode(result.getData());
            }
            map =  bankBeanDaoService.getPagingData(bankBean);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","获取失败");
        }
        return GsonUtil.toJson(map);
    }

    @RequestMapping("addBank")
    public String addBank(@Validated BankBean bankBean){
        CallResult<String> result = new CallResult<>();
        try {
            CallResult<String> bankCodeResult = getAreaCodeByLogin(AreaUserRoleEnum.AREA_USER_ROLE_SHIB.getCode());
            if(bankCodeResult.isExec()){
                bankBean.setAreaCode(bankCodeResult.getData());
            }else{
                return gson.toJson(bankCodeResult);
            }
            BankBean param = new BankBean();
            param.setBankCode(bankBean.getBankCode());
            BankBean b = bankBeanDaoService.getByField(param);
            if(b == null){
                String code = bankBeanDao.selectMaxCode(bankBean.getAreaCode());
                if (isEmpty(code)) {
                    code = bankBean.getAreaCode() + Constant.ENDCODE;
                } else {
                    code = StringUtil.getCode(6, code);
                }
                bankBean.setCode(code);
                bankBean.setCreateOn(new Date());
                bankBean.setCreateBy(String.valueOf(user_id_prikey));
                bankBean.setUpdateBy(String.valueOf(user_id_prikey));
                bankBean.setUpdateOn(new Date());
                bankBeanDaoService.add(bankBean);
                result.setCode(0);
                result.setMsg("操作成功");
            }else {
                result.setCode(400);
                result.setMsg("银行编号已存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }

    @RequestMapping("updateBank")
	public String updateBank(@Validated BankBean bankBean) {
		CallResult<String> result = new CallResult<>();
		try {
			if (bankBean.getId_prikey() == null) {
				result.setCode(400);
				result.setMsg("主键参数有误");
				return GsonUtil.toJson(result);
			}
			BankBean byId = bankBeanDaoService.getById(bankBean.getId_prikey());
			if (byId == null) {
				result.setCode(400);
				result.setMsg("参数有误");
				return GsonUtil.toJson(result);
			}
			if (!bankBean.getBankCode().equals(byId.getBankCode())) {
				BankBean bb = new BankBean();
				bb.setBankCode(bankBean.getBankCode());
				BankBean byField = bankBeanDaoService.getByField(bb);
				if (byField != null) {
					result.setCode(400);
					result.setMsg("银行编号已存在");
					return GsonUtil.toJson(result);
				}
			}
			bankBean.setUpdateOn(new Date());
			bankBean.setUpdateBy(String.valueOf(user_id_prikey));
			bankBeanDaoService.set(bankBean);
			result.setCode(0);
			result.setMsg("操作成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setCode(400);
			result.setMsg("操作失败");
			e.printStackTrace();
		}
		return GsonUtil.toJson(result);
	}

    @RequestMapping("deleteBank")
    public String deleteBank(Integer id_prikey){
        CallResult<String> result = new CallResult<>();
        try {
            if(id_prikey == null){
                result.setCode(400);
                result.setMsg("主键参数有误");
            }else{
                result = bankAreaService.removeById(id_prikey);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }


    @RequestMapping("getBankBranchList")
    public String getBankBranchList(BankBranchBean bankBranchBean){
        Map<String,Object> map = new HashMap<>();
        try {
            CallResult<String> areaCodeResult = getAreaCodeByLogin(AreaUserRoleEnum.AREA_USER_ROLE_Bank.getCode());
            if(areaCodeResult.isExec()){
                bankBranchBean.setAreaCode(areaCodeResult.getData());
            }
            map =  bankBranchBeanDaoService.getPagingData(bankBranchBean);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","获取失败");
        }
        return GsonUtil.toJson(map);
    }

    @RequestMapping("addBankBranch")
    public String addBankBranch(@Validated BankBranchBean bankBranchBean){
        CallResult<String> result = new CallResult<>();
        try {
            CallResult<String> bankCodeResult = getAreaCodeByLogin(AreaUserRoleEnum.AREA_USER_ROLE_Bank.getCode());
            if(bankCodeResult.isExec()){
                bankBranchBean.setAreaCode(bankCodeResult.getData());
            }else{
                return GsonUtil.toJson(bankCodeResult);
            }
            BankBean bankBeanParam = new BankBean();
            bankBeanParam.setCode(bankBranchBean.getAreaCode());
            BankBean bankBean = bankBeanDaoService.getByField(bankBeanParam);
            if(bankBean != null){
                bankBranchBean.setBankCode(bankBean.getBankCode());
            }
            String code = bankBranchBeanDao.selectMaxCode(bankBranchBean.getAreaCode());
            if (isEmpty(code)) {
                code = bankBranchBean.getAreaCode() + Constant.ENDCODE;
            } else {
                code = StringUtil.getCode(9, code);
            }
            bankBranchBean.setCode(code);
            bankBranchBean.setCreateOn(new Date());
            bankBranchBean.setCreateBy(String.valueOf(user_id_prikey));
            bankBranchBean.setUpdateBy(String.valueOf(user_id_prikey));
            bankBranchBean.setUpdateOn(new Date());
            bankBranchBeanDaoService.add(bankBranchBean);
            result.setCode(0);
            result.setMsg("操作成功");

        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }

    @RequestMapping("updateBankBranch")
    public String updateBankBranch(@Validated BankBranchBean bankBranchBean){
        CallResult<String> result = new CallResult<>();
        try {
            if(bankBranchBean.getId_prikey() == null){
                result.setCode(400);
                result.setMsg("主键参数有误");
            }else{
                bankBranchBean.setUpdateOn(new Date());
                bankBranchBean.setUpdateBy(String.valueOf(user_id_prikey));
                bankBranchBeanDaoService.set(bankBranchBean);
                result.setCode(0);
                result.setMsg("操作成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }

    @RequestMapping("deleteBankBranch")
    public String deleteBankBranch(Integer id_prikey){
        CallResult<String> result = new CallResult<>();
        try {
            if(id_prikey == null){
                result.setCode(400);
                result.setMsg("主键参数有误");
            }else{
                bankBranchBeanDaoService.removeOne(id_prikey);
                result.setCode(0);
                result.setMsg("操作成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }


    @RequestMapping("getBankAreaAdmin")
    public String getBankAreaAdmin(AreaUserBean areaUserBean){
        Map<String,Object> map = new HashMap<>();
        try {
            areaUserBean.setRoleType("1");
            map =  areaUserBeanDaoService.getPagingData(areaUserBean);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","获取失败");
        }
        return GsonUtil.toJson(map);
    }

    @RequestMapping("addBankAreaAdmin")
    public String addBankAreaAdmin(@Validated  AreaUserBean areaUserBean){
        CallResult<String> result = new CallResult<>();
        try {
            result = customerManagerService.addBankAreaAdmin(areaUserBean,String.valueOf(user_id_prikey));
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }


    @RequestMapping("updateBankAreaAdmin")
    public String updateBankAreaAdmin(@Validated  AreaUserBean areaUserBean){
        CallResult<String> result = new CallResult<>();
        try {
            result = customerManagerService.updateBankAreaAdmin(areaUserBean,String.valueOf(user_id_prikey));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return GsonUtil.toJson(result);
    }


    @RequestMapping("deleteBankAreaAdmin")
    public String deleteBankAreaAdmin(Integer id_prikey){
        CallResult<String> result = new CallResult<>();
        try {
            if(id_prikey == null){
                result.setCode(400);
                result.setMsg("参数有误");
                return  GsonUtil.toJson(result);
            }
            areaUserBeanDaoService.removeOne(id_prikey);
            result.setCode(0);
            result.setMsg("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }





    @RequestMapping("getBankAdmin")
    public String getBankAdmin(AreaUserBean areaUserBean){
        Map<String,Object> map = new HashMap<>();
        try {
           /* CallResult<String> result = getAreaCodeByLogin(AreaUserRoleEnum.AREA_USER_ROLE_SHIB.getCode());
            if(result.isExec()){
                areaUserBean.setCode(result.getData());
            }*/
            areaUserBean.setRoleType("2");
            map =  areaUserBeanDaoService.getPagingData(areaUserBean);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","获取失败");
        }
        return GsonUtil.toJson(map);
    }

    @RequestMapping("addBankaAdmin")
    public String addBankAdmin(@Validated  AreaUserBean areaUserBean){
        CallResult<String> result = new CallResult<>();
        try {
            result = customerManagerService.addBankAdmin(areaUserBean,String.valueOf(user_id_prikey));
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }

    @RequestMapping("getBankByLogin")
    public String getBankByLogin(){
        CallResult<BankBean> result = new CallResult<>();
        try {
            CallResult<String> codeResult = getAreaCodeByLogin(AreaUserRoleEnum.AREA_USER_ROLE_Bank.getCode());
            if(!codeResult.isExec()){
                return GsonUtil.toJson(codeResult);
            }
            BankBean bankParam = new BankBean();
            bankParam.setCode(codeResult.getData());
            BankBean  bankBean = bankBeanDaoService.getByField(bankParam);
            result.setCode(0);
            result.setMsg("操作成功");
            result.setData(bankBean);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }

    /**
     * 根据权限获取bankTree
     * @return
     */
    @RequestMapping("getBankTree")
    public String getBankTree(){
        CallResult<List<TreeVo>> result = new CallResult<>();
        try {
            CallResult<String> bankCodeResult = getAreaCodeByLogin(AreaUserRoleEnum.AREA_USER_ROLE_Bank.getCode());
            if(!bankCodeResult.isExec()){
                return GsonUtil.toJson(bankCodeResult);
            }
            BankBean bbParam = new BankBean();
            bbParam.setCode(bankCodeResult.getData());
            List<BankBean> list = bankBeanDaoService.getAll(bbParam);
            List<TreeVo> treeList = new ArrayList<>();
            for(BankBean bb : list) {
                TreeVo vo = new TreeVo();
                vo.setName(bb.getName());
                vo.setId(bb.getCode());
                treeList.add(vo);
                BankBranchBean param = new BankBranchBean();
                param.setAreaCode(bb.getCode());
                List<BankBranchBean> branchBeanList = bankBranchBeanDaoService.getAll(param);
                for (BankBranchBean branch : branchBeanList) {
                    TreeVo vo1 = new TreeVo();
                    vo1.setName(branch.getName());
                    vo1.setId(branch.getCode());
                    vo1.setPId(bb.getCode());
                    treeList.add(vo1);
                }
            }
            result.setCode(0);
            result.setMsg("操作成功");
            result.setData(treeList);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return GsonUtil.toJson(result);
    }

    public CallResult<String> getAreaCodeByLogin(String roleType) throws Exception{
        CallResult<String> result = new CallResult<>();
        AreaUserBean param = new AreaUserBean();
        param.setRoleType(roleType);
        param.setTel(hb_user.getName());
        AreaUserBean au = areaUserBeanDaoService.getByField(param);
        if(au == null || au.getCode() == null || "".equals(au.getCode())){
            result.setCode(400);
            result.setMsg("权限不足");
            return result;
        }else {
            result.setCode(0);
            result.setMsg("操作成功");
            result.setData(au.getCode());
        }
        return result;
    }

    /**
     * 获取区域银行树
     * @param param
     * @return
     */
    @PostMapping("getAreaAllTree")
    public String getAreaAllTree(String param) {
        CallResult result = bankAreaAuthService.getBankAreaAllTree(param);
        return gson.toJson(result);
    }

    /**
     * 获取区域和银行管理员
     * @param areaUserBean
     * @return
     */
    @PostMapping("getAllBankAreaAdmin")
    public String getAllBankAreaAdmin(AreaUserBean areaUserBean) {
        Map<String,Object> map = new HashMap<>();
        try {
            map =  areaUserBeanDaoService.getAllPaginData(areaUserBean);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","获取失败");
        }
        return GsonUtil.toJson(map);
    }

    /**
     * 权限分配
     * @param type
     * @param id
     * @param ids
     * @return
     */
    @PostMapping("addBankAreaAndUser")
    public String addBankAreaAndUser(String type, String id,String...ids) {
        CallResult<String> result = new CallResult<>();
        try {
            if (null == id || id.equals("")) {
                result.setCode(400);
                result.setMessage("id不能为空");
                return gson.toJson(result);
            }
            if (null != ids && ids.length > 0) {
                BankAreaAuthBean param = new BankAreaAuthBean();
                param.setUserId(id);
                List<BankAreaAuthBean> list = bankAreaAuthBeanDaoService.getAll(param);
                if (null != list && list.size() > 0) {
                    bankAreaAuthBeanDaoService.remove(param);
                }
                for (String AreaCode : ids) {
                    if (AreaCode.length() == 3) {
                        BankAreaAuthBean bA = new BankAreaAuthBean();
                        bA.setAreacode(AreaCode);
                        bA.setType(type);
                        bA.setUserId(id);
                        bankAreaAuthBeanDaoService.add(bA);
                    }
                    if (AreaCode.length() == 6) {
                        BankBean bankBean = new BankBean();
                        bankBean.setCode(AreaCode);
                        BankBean re = bankBeanDaoService.getByField(bankBean);
                        if (null != re) {
                            BankAreaAuthBean b = new BankAreaAuthBean();
                            b.setAreacode(AreaCode);
                            b.setBankcode(re.getBankCode());
                            b.setType(type);
                            b.setUserId(id);
                            bankAreaAuthBeanDaoService.add(b);
                        }
                    }
                }
                result.setCode(0);
                result.setMessage("保存成功");
            }else {
                BankAreaAuthBean bankAreaAuthBean = new BankAreaAuthBean();
                bankAreaAuthBean.setUserId(id);
                List<BankAreaAuthBean> list = bankAreaAuthBeanDaoService.getAll(bankAreaAuthBean);
                if (null != list && list.size() > 0) {
                    bankAreaAuthBeanDaoService.remove(bankAreaAuthBean);
                }
                result.setCode(0);
                result.setMessage("保存成功");
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMessage("保存失败");
        }
        return gson.toJson(result);
    }

    /**
     * 获取已分配的权限
     * @param id
     * @return
     */
    @PostMapping("getAuthList")
    public String getAuthList(String id,String code) {
        CallResult<List<String>> result = new CallResult<>();
        List<String> authList = new ArrayList<>();
        try {
            if (null == id || id.equals("")) {
                result.setCode(400);
                result.setMessage("id不能为空");
                return gson.toJson(result);
            }
            if (null == code || code.equals("")) {
                List<BankAreaAuthBean> li = bankAreaAuthBeanDaoService.getAuthList(id);
                for (BankAreaAuthBean data : li) {
                    if (data.getAreacode().length() == 3) {
                        authList.add(data.getAreacode());
                    }
                }
                result.setCode(0);
                result.setMessage("获取成功");
                result.setData(authList);
            }else {
                List<BankAreaAuthBean> li2 = bankAreaAuthBeanDaoService.getAuthList(id);
                for (BankAreaAuthBean data : li2) {
                    if (data.getAreacode().substring(0,3).equals(code) && data.getAreacode().length() == 6) {
                        authList.add(data.getAreacode());
                    }
                }
                result.setCode(0);
                result.setMessage("获取成功");
                result.setData(authList);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMessage("获取失败");
        }
        return gson.toJson(result);
    }
}
